import * as types from '../constants/ActionTypes'
import * as API_CONTRACTQUERY from '../apis/contractQuery'
import * as API_TABLE from '../apis/table'

import { WeaTable } from 'comsRedux'
const WeaTableAction = WeaTable.action;
import { Modal,message } from 'antd'

import objectAssign from 'object-assign'
import cloneDeep from 'lodash/cloneDeep'
import Immutable from 'immutable'

import { WeaTools } from 'ecCom'


//记录当前流程页
export const setNowRouterCmpath = value => {
	return { type: types.SET_NOW_ROUTER_PATH, path: value }
}

// 获得高级搜索表单项目
export const initDatas = params => {
	return(dispatch, getState) => {
		const viewScope = getState().crmcontractQuery.get('nowRouterCmpath');
		API_CONTRACTQUERY.getContractCondition().then((data1) => {
			API_CONTRACTQUERY.getCmTabs().then((data2) => {
				dispatch({
					type: `${viewScope}_` + types.INIT_CONDITION,
					conditionInfo: data1.datas,
					tabDatas:data2.datas,
					fromType:params
				});
			});
		});
	}
}

//搜索
export const doSearch = (params ) => {
	return(dispatch, getState) => {
		const viewScope = getState().crmcontractQuery.get('nowRouterCmpath');
		const searchParamsAd = getState()['crm' + viewScope].get('searchParamsAd').toJS();
		const selectedKey = getState()['crm' + viewScope].get('selectedKey');
		const fromType = getState()['crm' + viewScope].get('fromType').toJS();
		const tabParams = {tabType:selectedKey};
		const newParams = {...searchParamsAd, ...params,...tabParams,...fromType};
		dispatch({ type: viewScope + '_' + types.LOADING, loading: true });

		API_CONTRACTQUERY.getContractList(newParams).then((data) => {
			dispatch(WeaTableAction.getDatas(data.sessionkey,  1));
			dispatch({
				type:`${viewScope}_` + types.INIT_TABLE,
				dataKey: data.sessionkey,
				loading:false,
			});
		});
	}
}

// 审批合同信息
export const approveInfo = (contractId,operate) => {
    return(dispatch, getState) => {
		const viewScope = getState().crmcontractQuery.get('nowRouterCmpath');
		dispatch({ type: viewScope + '_' + types.LOADING, loading: true });
        API_CONTRACTQUERY.approveInfo({contractId:contractId}).then((data) => {
			dispatch({ type: viewScope + '_' + types.LOADING, loading: false });
			dispatch(doSearch());
			if(operate=="rightmenu"){
				dispatch(getContractInfo({contractId:contractId,operation:"view"},"1",true));
			}
        });
    }
}

// 合同签单完成
export const sign = (contractId,operate) => {
    return(dispatch, getState) => {
		const viewScope = getState().crmcontractQuery.get('nowRouterCmpath');
		dispatch({ type: viewScope + '_' + types.LOADING, loading: true });
        API_CONTRACTQUERY.sign({contractId:contractId}).then((data) => {
			dispatch({ type: viewScope + '_' + types.LOADING, loading: false });
			// 签单后，提醒数据可能会变化，所以重新请求
			dispatch(doSearch());
			dispatch(initDatas());
			if(operate=="rightmenu"){
				dispatch(getContractInfo({contractId:contractId,operation:"view"},"1",true));
			}
        });
    }
}

// 合同执行完成
export const complete = (contractId,operate) => {
    return(dispatch, getState) => {
		const viewScope = getState().crmcontractQuery.get('nowRouterCmpath');
		dispatch({ type: viewScope + '_' + types.LOADING, loading: true });
        API_CONTRACTQUERY.complete({contractId:contractId}).then((data) => {
			dispatch({ type: viewScope + '_' + types.LOADING, loading: false });
			dispatch(doSearch());
			if(operate=="rightmenu"){
				dispatch(getContractInfo({contractId:contractId,operation:"view"},"1",true));
			}
        });
    }
}

// 重新打开
export const statusBack = (contractId,operate) => {
    return(dispatch, getState) => {
		const viewScope = getState().crmcontractQuery.get('nowRouterCmpath');
		dispatch({ type: viewScope + '_' + types.LOADING, loading: true });
        API_CONTRACTQUERY.statusBack({contractId:contractId}).then((data) => {
			dispatch({ type: viewScope + '_' + types.LOADING, loading: false });
			dispatch(doSearch());
			if(operate=="rightmenu"){
				dispatch(getContractInfo({contractId:contractId,operation:"view"},"1",true));
			}
        });
    }
}
// 关闭合同卡片模态窗口
export const closeDialog = () => {
    return (dispatch,getState)=>{
	
		dispatch({
			type: types.CONTRACTQUERY_CLOSE_DIALOG, isShowDialog: false
		})
	}
}

//切换tab
export const changeTab=key=>{
    return { type: types.SET_DETAIL_TABKEY, key: key }
}

//高级搜索显隐控制
export const setShowSearchAd = bool => {
	return (dispatch, getState) => {
		const viewScope = getState().crmcontractQuery.get('nowRouterCmpath');
		dispatch({ type: viewScope + '_' + types.SET_SHOW_SEARCHAD, value: bool })
	}
}

//高级搜索表单内容
export const saveOrderFields = (value = {}) => {
	return (dispatch, getState) => {
		const viewScope = getState().crmcontractQuery.get('nowRouterCmpath');
		dispatch({ type: viewScope + '_' + types.SAVE_ORDER_FIELDS, value: value })
	}
}

//组件卸载时是否需要清除的数据
export const isClearNowPageStatus = bool => {
	return(dispatch, getState) => {
		const viewScope = getState().crmcontactQuery.get('nowRouterWfpath');
		dispatch({ type: viewScope + '_' + types.CLEAR_PAGE_STATUS, isToReq: bool })
	}
}

//组件卸载时需要清除的数据
export const unmountClear = bool => {
	return(dispatch, getState) => {
		const viewScope = getState().crmcontractQuery.get('nowRouterWfpath');
		dispatch({ type: viewScope + '_' + types.UNMOUNT_CLEAR, isToReq: bool })
	}
}

//模态框  里面tab切换
export const changeModalTab = key=>{
	return(dispatch, getState) => {
		dispatch({ type: types.CONTRACTQUERY_SET_MODAL_TAB, key: key })
	}
}

//合同共享 列表
export const getContractShareList =(params,key,bool) =>{
	return(dispatch, getState) => {
        API_CONTRACTQUERY.getContractShareList(params).then((data) => {
			if(data.status=="success"){
				dispatch({ 
					type: types.CONTRACTQUERY_SET_SHARELIST, 
					shareList:data.datas,
					contractId:params.contractId
				});
				dispatch(showDialog(key,bool));
			}else{
				message.error('请求失败,'+data.msgcode+"!");
			}
        });
	}
}
//显示模态框
export const showDialog = (key,bool) => {
    return (dispatch, getState) => {
		//const dialogPageType = status == 2 ? "edit" : "view";
        dispatch({ 
			type:types.CONTRACTQUERY_SHOW_DIALOG, 
			isShowDialog: true,
			dialogLoading:true,
			modleSelectTabKey:key,
			hasTab:bool
		}); 
    }
}
//暂时保存下分享数据
export const saveShareDatas = params =>{
	return(dispatch, getState) => {
        dispatch({ 
			type:types.CONTRACTQUERY_SAVE_SHAREDATA, 
			shareData: params,
		}); 
    }
}
//合同共享  保存
export const contractShareSave = params =>{
	return(dispatch, getState) => {
        API_CONTRACTQUERY.contractShareSave(params).then((data) => {
			if(data.status=="success"){
				dispatch(getContractShareList({contractId:params.contractId},"3",true));
			}else{
				message.error('请求失败,'+data.msgcode+"!");
			}
        });
    }
}

//合同相关交流 列表
export const getExchangeList =(params,key,bool) =>{
	return(dispatch, getState) => {
        API_CONTRACTQUERY.getExchangeList(params).then((data) => {
			if(data.status=="success"){
				dispatch({ 
					type: types.CONTRACTQUERY_SET_EXCHANGELIST, 
					exchangeList:data.datas,
					contractId:params.contractId
				});
				dispatch(showDialog(key,bool));
			}else{
				message.error('请求失败,'+data.msgcode+"!");
			}
        });
	}
}

//合同相关交流 新建留言
export const saveExchange =(params) =>{
	return(dispatch, getState) => {
        API_CONTRACTQUERY.saveExchange(params).then((data) => {
			if(data.status=="success"){
				dispatch(getExchangeList({contractId:params.contractId},"2",true));
			}else{
				message.error('请求失败,'+data.msgcode+"!");
			}
        });
	}
}

//合同打开  查看详情
export const getContractInfo = (params,key,bool,status)=>{
	//console.log(params,key,bool,status)
	return(dispatch, getState) => {
		let newParams={};
		if(status==0 || status){
			newParams = {contractId:params,operation:status == '2' ? "edit" : "view"}
		}else{
			newParams=params;
		}
		dispatch(saveInfoFields());
		
        API_CONTRACTQUERY.getContractInfo(newParams).then((data) => {
			if(data.status=="success"){
				dispatch({ 
					type: types.CONTRACTQUERY_SET_CONTRACTINFO, 
					contractId:newParams.contractId,
					mainTableInfo: data.datas.mainTable,
	                subTable1Info: data.datas.subTable1,
					subTable2Info: data.datas.subTable2,
					subTable3Info: data.datas.subTable3 || {},
					subTable4Info: data.datas.subTable4 || {},
					rightMenuInfo: data.datas.rightMenu,
					canEdit:data.datas.canEdit,
					dialogPageType:newParams.operation,
					status:data.datas.status
				});

				let fieldsObj =crmGetFields(data.datas.mainTable);	
				dispatch(saveInfoFields(fieldsObj));

				dispatch(showDialog(key,bool));
		
			}else{
				message.error('请求失败,'+data.msgcode+"!");
			}
        });
	}
}

// 编辑合同信息
export const editInfo = (contractId) => {
    return (dispatch, getState) => {
        const viewScope = getState().crmcontractQuery.get('nowRouterCmpath');
        dispatch({ type:types.CONTRACTQUERY_CLEAR_INFO});
        API_CONTRACTQUERY.getContractInfo({operation:"edit",contractId:contractId}).then((data) => {
            dispatch({
                type: types.CONTRACTQUERY_SET_CONTRACTINFO,
              //  dialogLoading:false,
                mainTableInfo: data.datas.mainTable,
                subTable1Info: data.datas.subTable1,
				subTable2Info: data.datas.subTable2,
				subTable3Info: {},
				subTable4Info: {},
				rightMenuInfo: data.datas.rightMenu,
				canEdit:data.datas.canEdit,
				dialogPageType:"edit",
				contractId:contractId
            });
        });
    }
}


//合同信息编辑绑定
export const saveInfoFields = (value = {}) => {
	return (dispatch, getState) => {
		const viewScope = getState().crmcontractQuery.get('nowRouterCmpath');
		dispatch({ type: types.CONTRACTQUERY_SAVE_INFO_FIELDS, value: value })
	}
}
//保存合同编辑必填字段
export const saveContractInfoRequire =arr=>{
	return (dispatch, getState) => {
		dispatch({ type: types.CONTRACTQUERY_SAVE_INFO_REQUIRE, value: arr })
	}
}
//保存合同编辑产品
export const saveContractProduct =data=>{
	return (dispatch, getState) => {
		dispatch({ type: types.CONTRACTQUERY_SAVE_INFO_PRODUCT, value: data })
	}
}
//保存合同编辑付款条件
export const saveContractPay =data=>{
	return (dispatch, getState) => {
		dispatch({ type: types.CONTRACTQUERY_SAVE_INFO_PAY, value: data })
	}
}
// 保存合同信息
export const saveInfo = (contractId) => {
    return(dispatch, getState) => {
        const viewScope = getState().crmcontractQuery.get('nowRouterCmpath');
		const infoFieldsAd = getState()['crm' + viewScope].get('infoFieldsAd').toJS();
		const infoRequire = getState()['crm' + viewScope].get('infoRequire').toJS();
		const productList = getState()['crm' + viewScope].get('productList').toJS();
		const payMethodList = getState()['crm' + viewScope].get('payMethodList').toJS();
		const params ={
			contractId:contractId || "",
			productList:JSON.stringify(productList),
			payMethodList:JSON.stringify(payMethodList),
			...infoFieldsAd
		}
		const require = (function(){
			for(let i=0;i<infoRequire.length;i++){
                if(!infoFieldsAd[infoRequire[i]]){
                    return false
                }
             }
            return true;
		})();
		const productrequire = (function(){
			for(let i=0;i<productList.length;i++){
                if(!productList[i]['productId'] || !productList[i]['unitId']||!productList[i]['number_n']||!productList[i]['price']||!productList[i]['currencyId']||!productList[i]['depreciation']||!productList[i]['sumPrice']||!productList[i]['planDate']){
                    return false
                }
             }
            return true;
		})();
		const payrequire = (function(){
			for(let i=0;i<payMethodList.length;i++){
                if(!payMethodList[i]['prjName'] || !payMethodList[i]['typeId']||!payMethodList[i]['payPrice']||!payMethodList[i]['payDate']){
                    return false
                }
             }
            return true;
		})();
		if(require && productrequire &&payrequire ){
			if(contractId){
				API_CONTRACTQUERY.saveInfo(params).then((data) => {
					dispatch(getContractInfo({contractId:contractId,operation:"view"},"1",true));
					dispatch({ type: types.CONTRACTQUERY_CLEAR_SAVE_INFO, value: data });
				});
			}else{
				const startdate = new Date().getTime(infoFieldsAd.startdate);
				const enddate = new Date().getTime(infoFieldsAd.enddate);
				if(startdate > enddate){
					API_CONTRACTQUERY.saveCreateInfo(params).then((data) => {   //合同新建的保存
						dispatch(getContractInfo({contractId:contractId,operation:"view"},"1",true));
						dispatch({ type: types.CONTRACTQUERY_CLEAR_SAVE_INFO, value: data });
					});
				}else{
					Modal.warning({
						title: '系统提示',
						content: '合同开始日期必须小于合同结束日期!',
					});
				}
			}
		}else{
			Modal.warning({
                title: '系统提示',
                content: '必填信息不完整!',
            });
		}
    }
}

//合同  付货保存  
export const payGoodsSave =params =>{
	return (dispatch,getState)=>{

		API_CONTRACTQUERY.payGoodsSave(params).then((data) => {
			if(data.status == "success"){
				dispatch(getContractInfo({contractId:params.contractId,operation:"edit"},"1",false));
				//dispatch({ type: types.CONTRACTQUERY_CLEAR_SAVE_INFO, value: data });
			}else{
				message.error('请求失败,'+data.msgcode+"!");
			}
			
		});
	}
}
//合同  付货删除 
export const payGoodsDelete =params =>{
	return (dispatch,getState)=>{
		API_CONTRACTQUERY.payGoodsDelete(params).then((data) => {
			if(data.status == "success"){
				dispatch(getContractInfo({contractId:params.contractId,operation:"edit"},"1",false));
				//dispatch({ type: types.CONTRACTQUERY_CLEAR_SAVE_INFO, value: data });
			}else{
				message.error('请求失败,'+data.msgcode+"!");
			}
			
		});
	}
}

//合同  付款保存  
export const paySave =params =>{
	return (dispatch,getState)=>{
		API_CONTRACTQUERY.paySave(params).then((data) => {
			if(data.status == "success"){
				dispatch(getContractInfo({contractId:params.contractId,operation:"edit"},"1",false));
				//dispatch({ type: types.CONTRACTQUERY_CLEAR_SAVE_INFO, value: data });
			}else{
				message.error('请求失败,'+data.msgcode+"!");
			}
			
		});
	}
}
//合同  付款删除 
export const payDelete =params =>{
	return (dispatch,getState)=>{
		API_CONTRACTQUERY.payDelete(params).then((data) => {
			if(data.status == "success"){
				dispatch(getContractInfo({contractId:params.contractId,operation:"edit"},"1",false));
				//dispatch({ type: types.CONTRACTQUERY_CLEAR_SAVE_INFO, value: data });
			}else{
				message.error('请求失败,'+data.msgcode+"!");
			}
			
		});
	}
}